/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component, Fragment } from 'react';
import { Form, Button, Badge, Radio, Tooltip, DatePicker, Descriptions, Tag, Icon, message, Modal, Drawer } from 'antd';
import { connect } from 'dva';
import forEach from 'lodash/forEach';
import request from '@/utils/request';
import { getTimeDistance,renderValveOpen ,download,formateObjToParamStr,renderSignalIntensity} from '@/utils/utils';
import moment from 'moment';
import ReactEcharts from 'echarts-for-react';
import ReactDataGrid from 'react-data-grid';
import find from 'lodash/find';
import gold from '../../images/gold.png';
import stop2 from '../../images/stop2.png';
import config from '../../config/config';
import Meter24Detail from '../Meters/Meter24Detail';
import AnnualBillings from './AnnualBillings';
import wechat from '../../images/wechat.png';
const { confirm } = Modal;
const ButtonGroup = Button.Group;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      detail: {owner:{}},
      meterDetail:{},
      totalVal: 0,
      showType: 1,
      historyData: [],
      valve_logs:[],
      payHistoryData: [],
      annualBillings:[],
      showCustom: false,
      rangePickerValue: [moment('2019' + '-01'+ '-' + '01', 'YYYY-MM-DD'), moment(new Date().getFullYear() + '-12'+ '-' + '31', 'YYYY-MM-DD')],
      meterRangePickerValue: [moment().add(-29, 'days'), moment(new Date().getFullYear() + '-12'+ '-' + '31', 'YYYY-MM-DD')],
    };
  }

  componentDidMount() {
    console.log(this.props)
    const that = this;
    that.fetchDetail();
    that.fetch();
    that.fetchMeter();
    that.fetchPayment();
    that.fetchSwitch_valve_logs();

  }
  onChangeShowType = e => {
    this.setState({
      showType: e.target.value,
    });
  };
  //获取基本信息
  fetchDetail = () => {
    const that = this;
    request(`/accounts/${this.props.id}`, {
      method: 'GET',
      params: {},
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          detail:response.data.data
        })
      }


    });
  };
  fetchMeter = () => {
    const that = this;
    console.log('this.props.meter_number',this.props.meter_number)
    request(`/meters/${escape(this.props.meter_number)}`, {
      method: 'GET',
      params: {},
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          meterDetail:response.data.data
        })
      }


    });
  };
  fetchSwitch_valve_logs=()=>{
    const that = this;
    request(`/switch_valve_logs`, {
      method: 'GET',
      params: {
        order_direction:'desc',
        meter_number:this.props.meter_number,
        start_date:'2020-06-11',
        end_date: moment(new Date()).format('YYYY-MM-DD')
      },
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          valve_logs:response.data.data
        })
      }


    });
  }
  isActive(type) {
    const { rangePickerValue } = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return false;
    }
    if (rangePickerValue[0].isSame(value[0], 'day') && rangePickerValue[1].isSame(value[1], 'day')) {
      return true;
    }
  }
  getOption = () => {
    const data=this.state.historyData;
    let Date=[];
    let Data=[];
    let diffData=[];
    let errDataIndex=[];
    let warmDataIndex=[];
    let difference_value=0
    forEach(data,(value,index)=>{
      Date.push(value.date);
      Data.push(value.value)
      if(value.status!==1){
        errDataIndex.push(index)
      }
      diffData.push(value.consumption)
    })

    let option = {
      background: 'rgba(0,0,0,1)',
      color: ['#3398DB','#fe5810'],
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['水表读数', '用水量'],
      },
      xAxis: [
        {
          type: 'category',
          data: Date,
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: '水表读数(柱状图)',
          axisLabel: {
            formatter: '{value}(m3)',
          },
        },
        {
          type: 'value',
          name: '用水量(折线图)',
          axisLabel: {
            formatter: '{value}(m3)',
          },
          splitLine: {
            show: false
          }
        },
      ],
      grid: {
        top: '14%',
        left: '2%',
        right: '2%',
        bottom: '4%',
        containLabel: true,
      },
      dataZoom: [
        {
          type: 'slider',
          show: false,
          xAxisIndex: [0],
        },
        {
          type: 'inside',
          xAxisIndex: [0],
        },
      ],
      series: [
        {
          name: '水表读数',
          type: 'bar',
          data:Data,
          itemStyle:{
            normal:{
              color: function(value) {
                if(errDataIndex.indexOf(value.dataIndex)>=0){
                  return '#c23531'
                } else{
                  return '#3398DB'
                }
              }
            }
          },
        },
        {
          name: '用水量',
          type: 'line',
          yAxisIndex: 1,
          symbolSize:8,
          data:diffData,
          smooth: true,
          itemStyle:{
            normal: {
              color: '#fe5810',
            }
          }
        },
      ],
    };
    return option;
  };
  selectDate = (type) => {
    const that = this;
    this.setState({
      rangePickerValue: getTimeDistance(type),
    }, function() {
      that.fetchPayment();
    });
  };
  //获取充值记录
  fetchPayment=(cb)=>{
    const that=this;
    request(`/payments`,{
      method:'GET',
      params:{
        account_id:this.props.id,
        start_date:that.state.rangePickerValue[0].format("YYYY-MM-DD"),
        end_date:that.state.rangePickerValue[1].format("YYYY-MM-DD"),
        order_direction:'desc',
        page:1,
        per_page:200
      }
    }).then((response)=>{
      console.log(response);
      if(response.status===200){
        this.setState({
          payHistoryData:response.data.data,
        })
      }

    });
  }
  //获取水表历史读数
  fetch=(cb)=>{
    const that=this;
    request(`/meter_historical_data`,{
      method:'GET',
      params:{
        meter_id:this.props.meter_number,
        start_date:that.state.meterRangePickerValue[0].format("YYYY-MM-DD"),
        end_date:that.state.meterRangePickerValue[1].format("YYYY-MM-DD"),
      }
    }).then((response)=>{
      console.log(response);
      if(response.status===200){
        this.setState({
          historyData:response.data.data,
          totalVal:response.data.total_consumption
        })
      }

    });
  }
  handleRangePickerChange = (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        rangePickerValue: [datePickerValue, this.state.rangePickerValue[1]],
      }, function() {
        that.fetchPayment();
      });
    } else {
      this.setState({
        rangePickerValue: [this.state.rangePickerValue[0], datePickerValue],
      }, function() {
        that.fetchPayment();
      });
    }
  };
  handleMeterRangePickerChange= (datePickerValue, type) => {
    const that = this;
    if (type === 'start') {
      this.setState({
        meterRangePickerValue: [datePickerValue, this.state.meterRangePickerValue[1]],
      }, function() {
        that.fetch();
      });
    } else {
      this.setState({
        meterRangePickerValue: [this.state.meterRangePickerValue[0], datePickerValue],
      }, function() {
        that.fetch();
      });
    }
  };
  ChangeValve=(value)=>{
    if(value===1){
      this.setState({
        openValveLoading:true,
      })
    }else{
      this.setState({
        closeValveLoading:true,
      })
    }
    const that=this;
    request(`/meter_valve_switch`,{
      method:'POST',
      data:{
        meter_ids:[this.props.meter_number],
        valve_status:value
      }
    }).then((response)=>{
      if(response.status===200){
        message.success(`${value===1?'开阀':'关阀'}指令下发成功`);
        that.fetchSwitch_valve_logs()
        setTimeout(function() {
          that.setState({
            openValveLoading:false,
            closeValveLoading:false,
          })
        },2000)
      }
    });
  }
  renderValueStatus=(val)=>{
    let status='success';
    let explain='';
    switch (val){
      case -4:
        status='error'
        explain= '错报'
        break;
      case -3:
        status='error'
        explain='抄表失败'
        break;
      case -2:
        status='warning'
        explain= '漏报'
        break;
      case -1:
        status='warning'
        explain= '未上报'
        break;
      default:
        status='success'
        explain= '正常'
    }
    return (
      <p>
        <Badge status={status}/>{explain}
      </p>
    )
  }
  handleExport=()=>{
    const payload= {
      meter_id:this.props.meter_number,
      start_date:this.state.meterRangePickerValue[0].format("YYYY-MM-DD"),
      end_date:this.state.meterRangePickerValue[1].format("YYYY-MM-DD"),
    }
    download(`${config.prefix}/meter_data_files?Authorization=Bearer ${sessionStorage.getItem('token')}&${formateObjToParamStr(payload)}`)
  }
  renderBatteryStatus=(value)=>{
    let status='success';
    let explain='';
    switch (value){
      case -1:
        status='warning'
        explain= '欠压'
        break;
      case 1:
        status='warning'
        explain= '正常'
        break;
      case 2:
        status='warning'
        explain= '未上报'
        break;
      default:
        status='success'
        explain= '正常'
    }
    return <span>{explain}</span>
  }
  render() {
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{event.value + 1}</p>;
        },
      },
      {
        name: '充值时间',
        width: 165,
        key: 'payment_time',
      },
      {
        name: '缴费金额',
        width: 100,
        key: 'amount',
        formatter:(event)=>{
          return <div className={`money ${event.value<0?'error':''}`}><img className={'gold'} src={gold} alt=""/>{event.value}</div>
        }
      },
      {
        name: '类型',
        width: 100,
        key: 'type',
        formatter: (event) => {
          let text=''
          switch (Number(event.value)) {
            case 1:
              text='现金';
              break;
            case 2:
              text='支票';
               break;
            case 3:
              text='银行卡';
               break;
            case 4:
              text='微信扫码';
               break;
            case 5:
              text='支付宝扫码';
              break;
            case 6:
              text='网银';
              break;
            case 30:
              text='补水';
              break;
            case 31:
              text='换表补水';
              break;
            case 11:
              text='公众号缴费';
              break;
            case 12:
              return "公众号建行";
            case 13:
              return '建行APP缴费';
            case 20:
              text='撤销缴费';
              break;
            default:
              break
          }
          return text
        }
      },
      {
        name: '操作员',
        width: 120,
        key: 'operator_name',
      },
      {
        name: '备注',
        width: 115,
        key: 'remark',
      },
      {
        name: '开票状态',
        width: 90,
        key: 'invoicing_status',
        formatter: (event) => {
          let text = '';
          switch (event.value) {
            case -3:
              text = '开票失败';
              break;
            case -2:
              text = '不允许开票';
              break;
            case -1:
              text = '未开票';
              break;
            case 1:
              text = '正在开票';
              break;
            case 2:
              text = '已开票';
              break;
          }
          return <span title={text}>{text}</span>;
        },
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));


    const meterColumns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          return <p className={'index'}>{event.value + 1}</p>;
        },
      },
      {
        name: '日期',
        width: 160,
        key: 'date',
        formatter: (event) => {
          return <p onClick={()=>{
            this.setState({
              date:event.value,
              meter_id:this.props.meter_number,
              show24Detail:true,
            })
          }} style={{color:'blue',cursor:'pointer'}} title={'点击查看当天24小时用水数据'}>{event.value}{(event.value===detail.last_billing_date||moment(event.value).isBefore(moment(detail.last_billing_date)))&&' (已扣费)'}</p>;
        },
      },
      {
        name: '状态',
        width: 100,
        key: 'status',
        formatter: (event) =>{
          return this.renderValueStatus(event.value)
        }
      },
      {
        name: '用水量(m3)',
        width: 100,
        key: 'consumption',
      },
      {
        name: '水表读数(m3)',
        width: 120,
        key: 'value',
      },
      {
        name: '水表读数(原始)',
        width: 200,
        key: 'original_value',
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    const valvecolumns= [
      {
        name: '序号',
        width: 50,
        key: '_index',
        formatter: (event) => {
          return <p className={'index'}>{event.value + 1}</p>;
        },
      },
      {
        name: '下发时间',
        width: 150,
        key: 'created_at',
      },
      {
        name: '下发指令',
        width: 100,
        key:'valve_status',
        formatter: (event) => {
          return renderValveOpen(event.value);
        },
      },
      {
        name: '状态',
        width: 100,
        key: 'status',
        formatter: (event) =>{
          let status='success';
          let explain='';
          switch (event.value){
            case -1:
              status='error'
              explain= '下发失败'
              break;
            case 1:
              status='success'
              explain='下发成功'
              break;
            default:
              status='warm'
              explain= '未知'
          }
          return (
            <p>
              <Badge status={status}/>{explain}
            </p>
          )
        }
      },
      {
        name: '操作员',
        width: 100,
        key: 'operator_name',
      },
      {
        name: '厂商名称',
        width: 100,
        key: 'vendor_name',
      },
      {
        name: '返回结果',
        width: 150,
        key: 'result',
        formatter: (event) => {
          return <Tooltip title={JSON.stringify(event.value)}>{JSON.stringify(event.value)}</Tooltip>
        },
      },

    ].map(c => ({  ...defaultColumnProperties,...c }));
    const { detail } = this.state;
    const reverceData = [...this.state.historyData].reverse();
    return (
      <div>
        <Descriptions column={4} title={<div>
          <span>户主基本信息</span>
        </div>} bordered>
          <Descriptions.Item label="户主姓名" span={4}><Tooltip
            title={detail.name}>{detail.name}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="户主编号"  span={2}>{detail.number}</Descriptions.Item>

          <Descriptions.Item label="户主电话" span={2}>{detail.mobile}</Descriptions.Item>
          <Descriptions.Item label="身份证号" span={2}>{detail.identity_number}</Descriptions.Item>
          <Descriptions.Item label="户主地址"  span={2}><Tooltip
            title={detail.address}>{detail.address}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="人数" span={2}>{detail.people_number}</Descriptions.Item>
          <Descriptions.Item label="所属区域" span={2}><Tooltip
            title={detail.region&&detail.region.full_name}>{detail.region&&detail.region.name}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="开户时间"  span={2}>{detail.created_at}</Descriptions.Item>
          <Descriptions.Item label="开户人"  span={2}>{detail.operator_name }</Descriptions.Item>
          <Descriptions.Item label="户主性质"  span={2}><Tooltip
            title={detail.account_nature}>{detail.account_nature}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="旧系统水表号"  span={2}>{detail.old_meter_number }</Descriptions.Item>

          <Descriptions.Item label="备注"  span={4}><Tooltip
            title={detail.remark}>{detail.remark}</Tooltip></Descriptions.Item>
        </Descriptions>
        <Descriptions title={<div style={{marginTop:'10px'}}>
          <span >水表基本信息</span>
          {
            detail.status===-1&&
            <span style={{float:'right',fontWeight:'normal',color:'red'}}><img style={{width:'50px',position:'relative',top:'-2px'}} src={stop2} alt=""/> 该水表已注销</span>
          }
          </div>} bordered>
          <Descriptions.Item label="水表号" span={2}><Tooltip
            title={detail.meter_number}>{detail.meter_number}</Tooltip></Descriptions.Item>
          <Descriptions.Item label="阀门状态"  span={2}>{renderValveOpen(detail.valve_status)}</Descriptions.Item>
          <Descriptions.Item label="电池状态"  span={2}>{this.renderBatteryStatus(detail.battery_status)}</Descriptions.Item>
          <Descriptions.Item label="信号强度"  span={2}>{renderSignalIntensity(detail.signal_intensity)}</Descriptions.Item>
          <Descriptions.Item label="当前余额"  span={2}><p className={Number(detail.balance)>=Number(detail.balance_alarm_amount)?
            'table-success table-status':
            Number(detail.balance) > 0?'table-warm table-status':'table-error table-status' }>{detail.balance}</p></Descriptions.Item>
          <Descriptions.Item label="余额报警金额"  span={2}>{detail.balance_alarm_amount}</Descriptions.Item>
          <Descriptions.Item label="累计缴费金额"  span={2}>{detail.cumulative_payment_amount}</Descriptions.Item>
          <Descriptions.Item label="用水性质"  span={2}>{detail.price_nature&&detail.price_nature.name}</Descriptions.Item>
          <Descriptions.Item label="一阶价格"  span={2}>{detail.price_nature&&detail.price_nature.level_one_price}</Descriptions.Item>
          <Descriptions.Item label="一阶污水处理费"  span={2}>{detail.price_nature&&detail.price_nature.level_one_sewage_price}</Descriptions.Item>
          <Descriptions.Item label="二阶价格"  span={2}>{detail.price_nature&&detail.price_nature.level_two_price}</Descriptions.Item>
          <Descriptions.Item label="二阶污水处理费"  span={2}>{detail.price_nature&&detail.price_nature.level_two_sewage_price}</Descriptions.Item>
          <Descriptions.Item label="三阶价格"  span={2}>{detail.price_nature&&detail.price_nature.level_three_price}</Descriptions.Item>
          <Descriptions.Item label="三阶污水处理费"  span={2}>{detail.price_nature&&detail.price_nature.level_three_sewage_price}</Descriptions.Item>
          <Descriptions.Item label="一阶水量"  span={2}>{detail.price_nature&&detail.price_nature.level_one_consumption}</Descriptions.Item>
          <Descriptions.Item label="二阶水量"  span={2}>{detail.price_nature&&detail.price_nature.level_two_consumption}</Descriptions.Item>
          {
            detail.price_nature&&detail.price_nature.level===3&&
              <Fragment>
                <Descriptions.Item label="当前阶梯扣费水量"  span={2}>{detail.annual_billings&&detail.annual_billings.length>0&&detail.annual_billings[detail.annual_billings.length-1].total_consumption}</Descriptions.Item>
                <Descriptions.Item label="当前阶梯等级"  span={2}>{detail.annual_billings&&detail.annual_billings.length>0&&detail.annual_billings[detail.annual_billings.length-1].level}<span onClick={()=>{
                  this.setState({
                    annualBillings:detail.annual_billings,
                    price_nature:detail.price_nature,
                    annualBillingsModal:true,

                  })
                }} style={{color:'blue',cursor:'pointer',marginLeft:'5px'}} >[查看历史]</span></Descriptions.Item>
              </Fragment>
          }

          <Descriptions.Item label="计费状态"  span={2}>{Number(detail.billing_status)===1?'计费':'不计费'}</Descriptions.Item>
          <Descriptions.Item label="欠费关阀"  span={2}>{Number(detail.arrears_status)===1?'启用':'不启用'}</Descriptions.Item>
          <Descriptions.Item label="水表底数"  span={2}><span style={{color:this.state.meterDetail.initial_value?'red':''}}>{this.state.meterDetail.initial_value}</span></Descriptions.Item>
          <Descriptions.Item label="水表厂商"  span={2}>{this.state.meterDetail.vendor_name}</Descriptions.Item>

        </Descriptions>

        {
          detail.buyer_name&&
          <Descriptions title={<div style={{marginTop:'10px'}}>
            <span >开票信息</span>
          </div>} bordered>
            <Descriptions.Item label="购方名称" span={2}><Tooltip
              title={detail.buyer_name}>{detail.buyer_name}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="购方税号" span={2}><Tooltip
              title={detail.buyer_tax_number}>{detail.buyer_tax_number}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="购方地址" span={2}><Tooltip
              title={detail.buyer_address}>{detail.buyer_address}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="发票推送邮箱" span={2}><Tooltip
              title={detail.invoice_push_email}>{detail.invoice_push_email}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="购方电话" span={2}><Tooltip
              title={detail.buyer_telephone}>{detail.buyer_telephone}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="发票推送手机" span={2}><Tooltip
              title={detail.invoice_push_mobile}>{detail.invoice_push_mobile}</Tooltip></Descriptions.Item>
            <Descriptions.Item label="购方银行账户" span={2}><Tooltip
              title={detail.buyer_bank_account}>{detail.buyer_bank_account}</Tooltip></Descriptions.Item>


          </Descriptions>
        }

        <h3 className={'ant-descriptions-title'} style={{ marginTop: '18px' }}>水表充值记录
        </h3>
        <div style={{marginBottom:'10px'}}>
          <ButtonGroup>
            <Button onClick={() => this.selectDate('month')} type={this.isActive('month') ? 'primary' : ''}>本月</Button>
            <Button onClick={() => this.selectDate('year')} type={this.isActive('year') ? 'primary' : ''}>本年</Button>
          </ButtonGroup>

          <DatePicker
            value={this.state.rangePickerValue[0]}
            allowClear={false}
            format="YYYY-MM-DD"
            style={{ width: 150 }}
            placeholder={'开始日期'}
            onChange={(e) => this.handleRangePickerChange(e, 'start')}
          />
          <DatePicker
            allowClear={false}
            value={this.state.rangePickerValue[1]}
            format="YYYY-MM-DD"
            placeholder={'结束日期'}
            style={{ width: 150 }}
            onChange={(e) => this.handleRangePickerChange(e, 'end')}
          />
        </div>
        <ReactDataGrid
          columns={columns}
          rowGetter={i => {
            return { ...this.state.payHistoryData[i], _index: i };
          }}
          rowsCount={this.state.payHistoryData.length}
          minHeight={212}
        />

        <h3 className={'ant-descriptions-title'} style={{marginTop:'18px'}}>水表历史读值 </h3>
          <div>
            <DatePicker
              value={this.state.meterRangePickerValue[0]}
              allowClear={false}
              format="YYYY-MM-DD"
              style={{ width: 150 }}
              placeholder={'开始日期'}
              onChange={(e) => this.handleMeterRangePickerChange(e, 'start')}
            />
            <DatePicker
              allowClear={false}
              value={this.state.meterRangePickerValue[1]}
              format="YYYY-MM-DD"
              placeholder={'结束日期'}
              style={{ width: 150 }}
              onChange={(e) => this.handleMeterRangePickerChange(e, 'end')}
            />
            <Radio.Group onChange={this.onChangeShowType} style={{marginLeft:'10px'}} value={this.state.showType}>
              <Radio value={1}>柱状图</Radio>
              <Radio value={2}>表格</Radio>
            </Radio.Group>

            <span style={{float:'right',marginLeft:'10px',fontWeight:'bold',fontSize:'16px'}}>用水量: {this.state.totalVal}(m3)</span>
          </div>

        <div style={{height:'260px',marginTop:'10px'}}>
          {
            this.state.showType===1?
              <Fragment>
                <ReactEcharts
                  option={this.getOption()}
                  style={{ height: '240px', width: '100%' }}
                  theme='my_theme'
                  //onChartReady={this.onChartReadyCallback}
                  //onEvents={EventsDict}
                />
                <p>注 : 蓝色柱状图表示当天水表读数上传正常,红色柱状图表示读数上传异常</p>
              </Fragment>:  <ReactDataGrid
                columns={meterColumns}
                rowGetter={i => {
                  return { ...reverceData[i], _index: i };
                }}
                rowsCount={reverceData.length}
                minHeight={260}
              />
          }
        </div>
        <Tooltip title={'导出前请先选择上方时间段'}>
          <Button block icon="export" type="primary"  style={{marginTop:'10px'}}

                  onClick={this.handleExport}
          >导出水表读数</Button>
        </Tooltip>


        {
          find(this.permissions, { name: "meter_switch" }) &&
          <Fragment>
            <h3 className={'ant-descriptions-title'} style={{marginTop:'30px'}}>水表操作</h3>
            <Button block icon="reload" type="primary" loading={this.state.openValveLoading} className={'btn-green'} style={{marginBottom:'10px'}}
                    disabled={(Number(detail.balance)<=0)&&!find(this.permissions, { name: "force_open_valve" })}
                    onClick={()=>{
                      const that=this;
                      confirm({
                        title: `确定要对${detail.meter_number} 开阀吗?`,
                        content: '请谨慎操作！',
                        okText: '确定',
                        okType: 'danger',
                        cancelText: '取消',
                        centered: true,
                        maskClosable: true,
                        onOk() {
                          that.ChangeValve(1)
                        },
                        onCancel() {
                          console.log('Cancel');
                        },
                      });
                    }}
            >开阀</Button>
            <Button icon="poweroff" type="danger"  loading={this.state.closeValveLoading} block style={{marginBottom:'10px'}}  onClick={()=>{
              const that=this;
              confirm({
                title: `确定要对${detail.meter_number} 关阀吗?`,
                content: '请谨慎操作！',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                centered: true,
                maskClosable: true,
                onOk() {
                  that.ChangeValve(-1)
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}
            >
              关阀
            </Button>
            {(Number(detail.balance)<=0&&!find(this.permissions, { name: "force_open_valve" }))&&
            <div style={{marginBottom:'10px',color:'red'}}>用户余额不大于0时，不能人工下发开阀</div>}
          </Fragment>
        }

        <h3 className={'ant-descriptions-title'}>开关阀记录
        </h3>
        <ReactDataGrid
          columns={valvecolumns}
          rowGetter={i => {
            return { ...this.state.valve_logs[i], _index: i };
          }}
          rowsCount={this.state.valve_logs.length}
          minHeight={212}
        />
        <Drawer
          title={`${this.state.date} 24小时用水数据详情`}
          placement="right"
          destroyOnClose
          onClose={() => {
            this.setState({
              show24Detail: false,
            });
          }}

          width={500}
          visible={this.state.show24Detail}
        >
          <Meter24Detail meter_id={this.props.meter_number} date={this.state.date}></Meter24Detail>
        </Drawer>
        <Drawer
          title={`${detail.name}阶梯信息历史`}
          placement="right"
          destroyOnClose
          onClose={() => {
            this.setState({
              annualBillingsModal:false,
              annualBillings:[]
            })
          }}

          width={700}
          visible={this.state.annualBillingsModal}
        >
          <AnnualBillings annualBillings={this.state.annualBillings}  account_id={this.props.id} price_nature={this.state.price_nature}/>
        </Drawer>
      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);
